﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using SettlersEngine;
using Ants;

namespace AntsBot
{
    public class Logger
    {
        StreamWriter log;
        public Logger()
        {
            log = File.CreateText("bot.log");
        }

        public void Log(string line)
        {
            log.WriteLine(line);
            log.Flush();
        }
    }

    public static class Utility
    {
        private static Logger log = new Logger();

        public static void Log(string line)
        {
            log.Log(line);
        }


        public static LinkedList<Tile> GetPath(Location loc1, Location loc2, GameState state)
        {
            if (Math.Abs(loc1.Col - loc2.Col) > state.ViewRadius2 || Math.Abs(loc1.Row - loc2.Row) > state.ViewRadius2)
            {
                Utility.Log("closest is a map wrap - try basic path function");
                var bpath = state.GetPath(loc1, loc2);
                //if(bpath.Count>0)
                return bpath;
                /*
                Log("use astar path for 3x3 map dupes ");
                var loc1center = new Location(state, loc1.Row + state.Height, loc1.Col + state.Width,false);
                Log("loc1center: " + loc1center);
                var loc2list = new List<Location>();
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        loc2list.Add(new Location(state, loc2.Row + (i * state.Height), loc2.Col + (j * state.Width), false));
                    }
                }
                var loc2close = loc2list.OrderBy(l => Math.Abs(l.Col - loc1center.Col) + Math.Abs(l.Row - loc1center.Row)).First();

                Log("loc2close: " + loc2close);
                var path = astarwrap.Search(loc1center.ToPoint(), loc2close.ToPoint(), new Object());
                var newpath = new LinkedList<Tile>();
                foreach (var tile in path)
                {
                    newpath.AddLast(new Tile(tile.Type, new Location(state, tile.Location.Row % state.Height, tile.Location.Col % state.Width)));
                }
                Log("newpath: " + String.Join(",", newpath.Select(t => t.Location.ToString())));
                return newpath;
                 * */
            }
            else
            {

                Utility.Log("use astar path function");
                var astar = state.AStar.Search(loc1.ToPoint(), loc2.ToPoint(), new Object());
                return astar ?? state.GetPath(loc1, loc2);
            }
        }
    }
}
